package com.example.linktop.myimageviewer;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private final int GETMAPSUCC = 1;
    private final int GETMAPFAIL = -1;

    private EditText ediTxt;//路径输入
    private ImageView imgV; //展示的图片

    private Handler thisHandle = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);



            switch (msg.what) {

                case GETMAPSUCC:
                    if (msg.obj != null && (msg.obj instanceof Bitmap)) {

                        imgV.setImageBitmap((Bitmap) msg.obj);


                    }
                    break;

                case GETMAPFAIL:
                    Toast.makeText(getApplicationContext(), "网络繁忙, 请稍后再试.",Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;
            }



        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//引入布局文件


        ediTxt = (EditText) findViewById(R.id.editxt);
        imgV = (ImageView) findViewById(R.id.imgV);

    }


    /*
    *  点击方法
    * */

    public void clickMethod (View v) {
        //按钮点击

//        开子线程

        new Thread(){

            public void run() {


                try {
                    //获取地址
                    String pathStr = ediTxt.getText().toString().trim();

                    String cacheFileName = Base64.encodeToString(pathStr.getBytes(), Base64.DEFAULT);

                    //检查图片是否缓存
                    final File fileCheck = new File(getCacheDir(),cacheFileName);
                    if (fileCheck.exists()) {
//                        Message msgCache = Message.obtain();
//                        msgCache.obj = BitmapFactory.decodeFile(fileCheck.getAbsolutePath()); //绝对路径
//                        thisHandle.sendMessage(msgCache);
                        //直接在ui线程更新
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                imgV.setImageBitmap(BitmapFactory.decodeFile(fileCheck.getAbsolutePath()));

                            }
                        });


                        return;

                    } else {



                    }




                    System.out.println("lzp : " + pathStr);

                    //获取url
                    URL url = new URL(pathStr);

                    //获取urlconnection对象
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //请求类型
                    connection.setRequestMethod("GET");
                    //超时时间
                    connection.setReadTimeout(5 * 1000); //5秒

                    //获取服务器返回码
                    if (connection.getResponseCode() == 200) {
                        //任何数据都是以流形式返回
                        InputStream stream =  connection.getInputStream();


                        //转换位图
                        Bitmap bitmap = BitmapFactory.decodeStream(stream);

                        //显示图片
                        Message msg = Message.obtain();

                        msg.obj = bitmap;
                        msg.what = GETMAPSUCC;
                        thisHandle.sendMessage(msg);
                        //保存图片做缓存
                        File cacheFiel = new File(getCacheDir(), cacheFileName);
                        FileOutputStream fot = new FileOutputStream(cacheFiel);
                        int len = -1;
                        byte[] buff = new  byte[1024]; //1k
                        while ((len = stream.read(buff)) != -1) {
                            fot.write(buff, 0, len);

                        }

//                        System.out.println("Stream长度:" + stream.toString().length());

                        fot.close();//关闭输出流

                        stream.close();


                    } else  {
                        //失败
                        Message msg = Message.obtain();
                        msg.what = GETMAPFAIL;
                        thisHandle.sendMessage(msg);

                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

        }.start();




    }
}
